package com.yusp75.myexam.com.yusp75.myexam.util

import android.Manifest.permission.READ_EXTERNAL_STORAGE
import android.Manifest.permission.READ_MEDIA_IMAGES
import android.content.Context
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.os.Build
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.FragmentActivity

class PermissionUtils {

    // 检查权限状态
    fun Context.hasFileReadPermission(): Boolean {
        return if (Build.VERSION.SDK_INT >= 33) {
            checkSelfPermission(READ_MEDIA_IMAGES) == PERMISSION_GRANTED
        } else {
            checkSelfPermission(READ_EXTERNAL_STORAGE) == PERMISSION_GRANTED
        }
    }

    // 请求权限扩展函数
    fun FragmentActivity.requestFilePermission(
        onGranted: () -> Unit,
        onDenied: (permissions: List<String>) -> Unit
    ) {
        val permissions = when {
            Build.VERSION.SDK_INT >= 33 -> arrayOf(READ_MEDIA_IMAGES)
            else -> arrayOf(READ_EXTERNAL_STORAGE)
        }

        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { results ->
            when {
                results.all { it.value } -> onGranted()
                else -> onDenied(results.filter { !it.value }.keys.toList())
            }
        }.launch(permissions)
    }

}